package org.shoukaiseki.tencent.live.utils;

import org.apache.commons.lang3.StringUtils;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * org.shoukaiseki.tencent.live.utils.TencentLiveUtils
 * <br>
 *
 * @author shoukaiseki ブログ http://www.shoukaiseki.top/<br> E-メール jiang28555@Gmail.com<br>
 * @date 2020-12-19 15:38:16<br>
 */
public class TencentLiveUtils {



    private static final char[] DIGITS_LOWER =
            {'0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f'};

    /*
     * KEY+ streamName + txTime
     */
    public static String getSafeUrl(String key, String streamName, long txTime) {
        String input = new StringBuilder().
                append(key).
                append(streamName).
                append(Long.toHexString(txTime).toUpperCase()).toString();

        String txSecret = null;
        try {
            MessageDigest messageDigest = MessageDigest.getInstance("MD5");
            txSecret  = byteArrayToHexString(
                    messageDigest.digest(input.getBytes("UTF-8")));
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        return txSecret == null ? "" :
                new StringBuilder().
                        append("txSecret=").
                        append(txSecret).
                        append("&").
                        append("txTime=").
                        append(Long.toHexString(txTime).toUpperCase()).
                        toString();
    }

    private static String byteArrayToHexString(byte[] data) {
        char[] out = new char[data.length << 1];

        for (int i = 0, j = 0; i < data.length; i++) {
            out[j++] = DIGITS_LOWER[(0xF0 & data[i]) >>> 4];
            out[j++] = DIGITS_LOWER[0x0F & data[i]];
        }
        return new String(out);
    }


    /**
     * 活跃
     */
    public static final String ACTIVE="active";
    /**
     * 非活跃
     */
    public static final String INACTIVE="inactive";
    /**
     * 禁播
     */
    public static final String FORBID="forbid";

    /**
     * 频道状态转换为数字状态
     * @param streamState  腾讯云返回的状态
     * @return  0:云频道播放中，1:非活跃,4:禁播
     */
    public static Integer streamStateToInteger(String streamState) {
        if(StringUtils.equals(ACTIVE,streamState)) {
            return 0;
        }else if(StringUtils.equals(INACTIVE,streamState)) {
            return 1;
        }else if(StringUtils.equals(FORBID,streamState)) {
            return 4;
        }
        return -1;
    }

}
